package service

import (
	"demo/basic/config"
	"demo/handler/model"
	"demo/handler/request"
	"demo/pkg"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"math/rand"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	var user model.User
	if err := user.IsUser(config.DB, form.Phone); err == nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "手机号已注册"})
		return
	}
	smsCode, _ := config.Rdb.Get(config.Ctx, "smsCode_"+form.Phone).Result()
	if smsCode != form.SmsCode {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "验证码错误"})
		return
	}
	user = model.User{
		Phone:     form.Phone,
		Password:  pkg.Md5(form.Password),
		NickName:  fmt.Sprintf("游客_%d", rand.Intn(10000)),
		AvatarUrl: fmt.Sprintf("%s.png", uuid.New().String()),
		Refer:     "还未填写个性签名",
	}
	if err := user.Register(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "注册失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "注册成功"})
	return
}

func Login(c *gin.Context) {
	var form request.Login
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	var user model.User
	if err := user.IsUser(config.DB, form.Phone); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "手机号未注册"})
		return
	}
	if user.Password != pkg.Md5(form.Password) {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "密码错误"})
		return
	}
	token, err := pkg.GetJwtToken(int(user.ID))
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": gin.H{
			"user":      user.Phone,
			"nickName":  user.NickName,
			"avatarUrl": user.AvatarUrl,
			"refer":     user.Refer,
			"token":     token,
		},
	})
	return
}
func GetUser(c *gin.Context) {
	userId := c.GetFloat64("userId")
	var user model.User
	if err := user.GetUser(config.DB, int(userId)); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "查询用户信息失败"})
		return
	}
	key := fmt.Sprintf("userInfo%d", int(userId))
	cacheList, _ := config.Rdb.Get(config.Ctx, key).Result()
	if cacheList == "" {
		jsonStr, _ := json.Marshal(&user)
		config.Rdb.Set(config.Ctx, key, jsonStr, time.Minute*10)
	} else {
		json.Unmarshal([]byte(cacheList), &user)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询用户信息成功",
		"data": gin.H{
			"info": user,
		},
	})
	return

}
